package com.demo.shiro.controlloer;

import com.demo.shiro.model.UserInfo;
import com.demo.shiro.service.UserInfoService;
import com.demo.shiro.utils.ResponseBo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author Jmy
 * @date 2019/7/29 22:33
 * @email jiaomingyu5778@gmail.com
 */
@Api(value = "用户Controller")
@Controller
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;


    @ApiIgnore
    @GetMapping("hello")
    public @ResponseBody String hello() {
        return "hello";
    }

    /**
     * 查询用户信息，需要有用户权限
     * @return
     */
    @ApiOperation(value = "获取全部用户信息", notes = "获取系统中所有用户信息，需要user权限")
    @RequiresPermissions("user:user")
    @GetMapping("/list")
    public @ResponseBody ResponseBo userList(){
        List<UserInfo> userInfoList = userInfoService.selectAll();
        HashMap<String,Object> rtnMap = new HashMap<>();
        rtnMap.put("userList", userInfoList);
        return ResponseBo.ok(rtnMap);
    }

    @ApiOperation(value = "添加用户", notes = "添加用户信息，需要add权限")
    @ApiImplicitParam(name = "userInfo", value = "用户实体", required = true, dataType = "UserInfo")
    @RequiresPermissions("user:add")
    @PostMapping("/add")
    public @ResponseBody ResponseBo addUser(@RequestBody UserInfo userInfo){
        int rtnNum = userInfoService.inset(userInfo);
        if (rtnNum == 0) {
            return ResponseBo.error("用户信息不能为空！");
        }
        if (rtnNum == -1) {
            return ResponseBo.error("用户信息已存在！");
        }
        return ResponseBo.ok("添加用户成功！");
    }

    @ApiOperation(value = "删除用户", notes = "根据用户ID，删除用户信息。需要delete权限")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequiresPermissions("user:delete")
    @PutMapping("/{id}")
    public @ResponseBody ResponseBo deleteUser(@PathVariable(value = "id") Long id){
        int rtnNum = userInfoService.delete(id);
        if (rtnNum == 1) {
            return ResponseBo.ok("删除用户成功！");
        }
        return ResponseBo.error("删除用户失败！");
    }
}
